package com.pca.headline.controller;

import com.pca.headline.common.Result;
import com.pca.headline.common.ResultCodeEnum;
import com.pca.headline.pojo.NewsHeadline;
import com.pca.headline.service.NewsHeadlineService;
import com.pca.headline.service.impl.NewsHeadlineServiceImpl;
import com.pca.headline.util.JwtHelper;
import com.pca.headline.util.WebUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/headline/*")
public class NewsHeadlineController extends BaseController{
private NewsHeadlineService newsHeadlineService = new NewsHeadlineServiceImpl();


    protected void publish(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String token = req.getHeader("token");
        Long userId = JwtHelper.getUserId(token);
        //通过token获得用户id
        NewsHeadline newsHeadline = WebUtil.readJson(req,NewsHeadline.class);
        newsHeadline.setPublisher(userId.intValue());

        int rows = newsHeadlineService.addNewsHeadline(newsHeadline);
        Result .build(null, ResultCodeEnum.NOTLOGIN);

        WebUtil.writeJson(resp,Result.ok(null));



    }


//    protected void removeByHid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        String token = req.getHeader("token");
//        int id = Integer.parseInt(req.getParameter("id"));
//        Long userId = JwtHelper.getUserId(token);
//    }


    protected void findHeadlineByHid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int hid = Integer.parseInt(req.getParameter("hid"));
        Map data = new HashMap();
        NewsHeadline headline = newsHeadlineService.findByHid(hid);
        data.put("headline", headline);
        Result result = Result.ok(data);
        WebUtil.writeJson(resp,result);
    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取数据
        NewsHeadline headline = WebUtil.readJson(req, NewsHeadline.class);

        int rows = newsHeadlineService.updateNewsHeadline(headline);
        Result result = Result.ok(null);
        if(rows > 0){
            WebUtil.writeJson(resp,result);
        }
        WebUtil.writeJson(resp,Result.build(null,ResultCodeEnum.NOTLOGIN));
    }


    protected void removeByHid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int hid = Integer.parseInt(req.getParameter("hid"));
        int rows = newsHeadlineService.removeByHid(hid);
        Result result = Result.ok(null);
        if(rows > 0){
            WebUtil.writeJson(resp,result);
        }
        WebUtil.writeJson(resp,Result.build(null,ResultCodeEnum.NOTLOGIN));
    }
}
